const fs      = require('fs');
const path    = require('path');
const log     = require('fancy-log');
const fsextra = require('fs-extra');
const _       = require('lodash');
const async   = require('async');


const assets_dir = path.resolve(__dirname, '../../laya/assets/');


async function getPlayerListAssets() {
	return new Promise(resolve=> {
		let player_res = fsextra.readJSONSync(path.resolve(__dirname, '../data/player_list.json'));
		let player_list = player_res['player'];
		let assets_list = [];

		async.each(player_list, async (item, callback)=> {
			let skin_data = await getRoleAssets(item.no, item.skin);
			assets_list = assets_list.concat(skin_data);
			callback();
		}, error=> {
			let temp = [];
			let list = assets_list.filter(v=> {
				if (!temp.includes(v.url)) {
					temp.push(v.url);
					return true;
				}
				return false;
			});
			// console.log(list);
			resolve(list);
		});
	});

}
exports.getPlayerListAssets = getPlayerListAssets;


async function getRoleAssets(role_no, skin_id) {
	let assets_data = await getRoleAssetData();
	return new Promise((resolve, reject)=> {
		let role_assets = assets_data[role_no];
		if (Array.isArray(role_assets)) return resolve(role_assets);
		let skin_data = role_assets[skin_id];
        
		if (!skin_data) return reject(new Error('no skin data'));
		let origin_assets = skin_data.filter(v=> /skin_defult\.json$/i.test(v.url));
        
		async.each(origin_assets, (v, callback)=> {
			getDataAssetsList(v.url).then(data=> {
				skin_data.push(...data);
				callback();
			});
		}, error=> {
			resolve(skin_data);
		});
	});
};
exports.getRoleAssets = getRoleAssets;

/** 读取role_assets */
async function getRoleAssetData() {
	return new Promise(resolve=> {
		let assets_data = fsextra.readJSONSync(path.resolve(__dirname, '../data/role_assets.json'));
		resolve(assets_data);
	});
}

/** 获取skin_defult.json资源列表 */
async function getDataAssetsList(url) {
	return new Promise(resolve=> {
		let dir = path.join(assets_dir, url);
		let data = fsextra.readJSONSync(dir);
		resolve(data);
	});
}